package com.jxaummd.aquaculture.main;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;

import com.jxaummd.aquaculture.R;
import com.jxaummd.aquaculture.entity.event.MqttMessageEvent;
import com.jxaummd.aquaculture.entity.event.MqttMessageReciveEvent;
import com.jxaummd.aquaculture.ui.fragment.MainFragment;
import com.jxaummd.aquaculture.ui.fragment.first.FirstTabFragment;
import com.jxaummd.aquaculture.util.listener.IGetMessageCallBack;
import com.jxaummd.aquaculture.util.service.MQTTService;
import com.jxaummd.aquaculture.util.service.MyServiceConnection;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import me.yokeyword.fragmentation.SupportActivity;
import me.yokeyword.fragmentation.anim.DefaultHorizontalAnimator;
import me.yokeyword.fragmentation.anim.FragmentAnimator;


public class MainActivity extends SupportActivity {
    private MyServiceConnection serviceConnection;
    private MQTTService mqttService;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
        if (findFragment(FirstTabFragment.class) == null) {
            loadRootFragment(R.id.fl_container, FirstTabFragment.newInstance());
        }
        initService();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void sendMessage(MqttMessageEvent event) {
        serviceConnection.sendMag(event.topic, event.message);
    }


    /**
     * 初始化系统服务
     */
    private void initService() {
        serviceConnection = new MyServiceConnection();
        serviceConnection.setIGetMessageCallBack(new IGetMessageCallBack() {
            @Override
            public void setMessage(String message,String topic) {
                EventBus.getDefault().post(new MqttMessageReciveEvent(message,topic));
            }
        });
        Intent intent = new Intent(this, MQTTService.class);
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    public void onBackPressedSupport() {
        // 对于 4个类别的主Fragment内的回退back逻辑,已经在其onBackPressedSupport里各自处理了
        super.onBackPressedSupport();
    }

    @Override
    public FragmentAnimator onCreateFragmentAnimator() {
        // 设置横向(和安卓4.x动画相同)
        return new DefaultHorizontalAnimator();
    }


    @Override
    protected void onDestroy() {
        unbindService(serviceConnection);
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
